// import { useEffect, useState } from "react";
import { useRequest } from "ahooks";
import { useParams } from "react-router-dom";
import { getQuestionServices } from "../services/question";
import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { resetComponents } from "@/store/componentReducer";
import { resetPageInfo } from "@/store/pageInfoReducer";
function useLoadQuestionData() {
  const { id = "" } = useParams();
  const dispatch = useDispatch();

  const { data, loading, error, run } = useRequest(
    async (id: string) => {
      if (!id) throw new Error("没有问卷id");
      const data = await getQuestionServices(id);
      return data;
    },
    {
      manual: true,
    }
  );

  useEffect(() => {
    if (!data) return;
    const {
      title = "",
      componentList = [],
      desc = "",
      css = "",
      js = "",
      isPublished = false,
    } = data;

    //获取默认的selectId
    let selectedId = "";
    if (componentList.length > 0) {
      selectedId = componentList[0].fe_id;
    }

    dispatch(
      resetComponents({
        componentList,
        selectId: selectedId,
        copiedComponent: void 0,
      })
    );
    dispatch(
      resetPageInfo({
        title,
        desc,
        css,
        js,
        isPublished,
      })
    );
  }, [data, dispatch]);

  useEffect(() => {
    run(id);
  }, [id, run]);

  return {
    loading,
    error,
  };
}

export default useLoadQuestionData;
